package core

import (
	"context"
	"encoding/json"
	"ez/apps/core/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Route struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64      `json:"id" bson:"id,omitempty"`
	AppId       string     `json:"appId" bson:"appId"`         //APPID
	From        string     `json:"from" bson:"from"`           //From
	To          string     `json:"to" bson:"to"`               //To
	IsOn        bool       `json:"isOn" bson:"isOn"`           //启用
	Sort        int64      `json:"sort" bson:"sort"`           //权重
	GateWay     *GateWay   `json:"gateWay" bson:"gateWay"`     //所属网关
	GateWayId   int64      `json:"gateWayId" bson:"gateWayId"` //所属网关
	CreateAt    time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *Route) DocName() string { return "Route" }
func (this *Route) GetId() int64    { return this.Id }
func (this *Route) SetId(id int64)  { this.Id = id }
func (this *Route) Create() error {
	return this.GetFactory().Create(this)
}
func (this *Route) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *Route) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Route) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *Route) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Route) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *Route) ToString() string {
	return string(this.ToBytes())
}
func (this *Route) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Route) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Route) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *Route) LoadGateWay() {
	if this.GateWayId == 0 {
		return
	}
	this.GateWay, _ = NewGateWayCrud().FindId(this.GateWayId)
}
func (this *Route) ClearRelationsBeforeSave() mgo.Doc {
	this.GateWay = nil
	return this
}
func neverUsed_Route() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type RouteAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Route
	Session *ez.Session
}

func NewRouteAccessControl(model *Route, action string, session *ez.Session) *RouteAccessControl {
	ctrl := &RouteAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.RouteAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
